package time_task

//统计代理产生的数据
import (
	"fmt"

	. "chess_platform/internal/common"
	"chess_platform/models/h5"
	"github.com/astaxie/beego/orm"
)

//代理的基本信息
type AgentBasicInfo struct {
	Uid           int64  `json:"uid"`
	Pid           int64  `json:"pid"`   //代理的上级代理的id
	Level         int64  `json:"level"` //代理的等级
	AgentNickname string `json:"agent_nickname"`
	GroupId       int64  `json:"group_id"`
	GroupName     string `json:"group_name"`
}

//代理的原始统计数据
type AgentRaw struct {
	Buy         int64 `json:"buy"`
	Give        int64 `json:"give"`
	Auto        int64 `json:"auto"`
	Handle      int64 `json:"handle"`
	Rest        int64 `json:"rest"`
	Cash        int64 `json:"cash"`
	AgentNum    int64 `json:"agent_num"`
	AgentOrder  int64 `json:"agent_order"`
	PlayerOrder int64 `json:"player_order"`
	Bonus       int64 `json:"bonus"`
}

//代理增长
type AgentGrowth struct {
	BuyGrowth         int64 `json:"buy_growth"`
	GiveGrowth        int64 `json:"give_growth"`
	AutoGrowth        int64 `json:"auto_growth"`
	HandleGrowth      int64 `json:"handle_growth"`
	RestGrowth        int64 `json:"rest_growth"`
	CashGrowth        int64 `json:"cash_growth"`
	AgentNumGrowth    int64 `json:"agent_num_growth"`
	AgentOrderGrowth  int64 `json:"agent_order_growth"`
	PlayerOrderGrowth int64 `json:"player_order_growth"`
}

//代理的信息
type AgentInfo struct {
	CreateTime    int64  `json:"create_time"`
	AgentId       int64  `json:"agent_id"`
	AgentNickname string `json:"agent_nickname"`
	GroupId       int64  `json:"group_id"`
	GroupName     string `json:"group_name"`
}

//大区名下所有的代理提成
type AgentBonus struct {
	AgentOrder        int64 `json:"agent_order"`
	PlayerOrder       int64 `json:"player_order"`
	AgentOrderGrowth  int64 `json:"agent_order_growth"`
	PlayerOrderGrowth int64 `json:"player_order_growth"`
}

//代理统计
type AgentStat struct {
	//AgentRaw
	Buy      int64 `json:"buy"`
	Give     int64 `json:"give"`
	Auto     int64 `json:"auto"`
	Handle   int64 `json:"handle"`
	Rest     int64 `json:"rest"`
	Cash     int64 `json:"cash"`
	AgentNum int64 `json:"agent_num"`
	//AgentGrowth
	BuyGrowth    int64 `json:"buy_growth"`
	GiveGrowth   int64 `json:"give_growth"`
	AutoGrowth   int64 `json:"auto_growth"`
	HandleGrowth int64 `json:"handle_growth"`
	RestGrowth   int64 `json:"rest_growth"`
	CashGrowth   int64 `json:"cash_growth"`

	AgentOrderGrowth  int64 `json:"agent_order_growth"`
	PlayerOrderGrowth int64 `json:"player_order_growth"`
}

//代理统计展示需要的信息
type AgentAll struct {
	//AgentInfo
	CreateTime    int64  `json:"create_time"`
	AgentId       int64  `json:"agent_id"`
	AgentNickname string `json:"agent_nickname"`
	GroupId       int64  `json:"group_id"`
	GroupName     string `json:"group_name"`

	//AgentStat
	Buy      int64 `json:"buy"`
	Give     int64 `json:"give"`
	Auto     int64 `json:"auto"`
	Handle   int64 `json:"handle"`
	Rest     int64 `json:"rest"`
	Cash     int64 `json:"cash"`
	AgentNum int64 `json:"agent_num"`

	AgentOrder  int64 `json:"agent_order"`
	PlayerOrder int64 `json:"player_order"`

	BuyGrowth      int64 `json:"buy_growth"`
	GiveGrowth     int64 `json:"give_growth"`
	AutoGrowth     int64 `json:"auto_growth"`
	HandleGrowth   int64 `json:"handle_growth"`
	RestGrowth     int64 `json:"rest_growth"`
	CashGrowth     int64 `json:"cash_growth"`
	AgentNumGrowth int64 `json:"agent_num_growth"`

	AgentOrderGrowth  int64 `json:"agent_order_growth"`
	PlayerOrderGrowth int64 `json:"player_order_growth"`
}

type CardNum struct {
	CardNum int64 `json:"card_num"`
	Type    int64 `json:"type"`
}

/*
代理数量:
	1. 一级代理有代理数概念,代理数:只包括名下的二级代理数,  日增长:当天实时代理数比上一天, 月增长:当月实时代理数比上个月
	2. 大区代理有代理数概念,代理数:只包括名下的所有代理(一级及二级), 日增长:当天实时代理数比上一天,月增长:当月实时代理比上个月
*/

//每天凌晨执行，统计昨天的数据
//统计每天代理消耗的房卡,收入方面的数据
func StatAgent(r map[int64]int64) error {
	LogPc.Info("-----------------进入统计代理函数----------------------------")
	//统计所有代理的情况
	ForExecute(listAllDayAgent, RecordDayAllAgent, r[RecordDayAllAgent])
	//在上面的基础上统计一级代理的数据(一级代理的数据包括一级代理本身及名下二级代理的数据)
	ForExecute(listDayLevel1Agent, RecordDayLevel1Agent, r[RecordDayLevel1Agent])
	//在上面基础上统一大区名下所有一级代理的数据(即所有代理的数据)
	ForExecute(listDayGroup, RecordDayGroup, r[RecordDayGroup])
	//在上面的基础上,统计月报表
	ForExecute(listAllMonthAgent, RecordMonthAgent, r[RecordMonthAgent])
	ForExecute(listMonthLevel1Agent, RecordMonthLevel1Agent, r[RecordMonthLevel1Agent])
	ForExecute(listMonthGroup, RecordMonthGroup, r[RecordMonthGroup])
	LogPc.Info("-----------------退出统计代理函数----------------------------")
	return nil
}

func listAllDayAgent(t int64) error {
	//现在统计以前的数据，会把今天才注册的新代理也记录在以前时间的表里，因为现在的新注册的代理不存在以前
	//但这不影响，因为统计出来是没有数据的，不影响，因为我没有做时间限制才会出现这种情况
	var count int64                                                                                                                       //先统计有多少个正式的代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			status = %v AND level != 0
	`, TableH5User, FirstTopUpSuccess) //level != 0 把系统账号排除掉
	o := NewDBOrm(DBChessCenter)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //没有正式代理，统计毛线
		LogPc.Info("暂时没有正式代理可以统计")
		return nil
	}
	//代理基本信息,pid,nickname,group_id,group_name
	sqlAgentInfo := fmt.Sprintf(`
			SELECT
				u.uid,u.pid,u.nickname AS agent_nickname,u.group_id,u.level,
				g.name AS group_name
			FROM
				%v AS u
			LEFT JOIN
				%v AS g
			ON u.group_id = g.id
			WHERE
				u.status = %v AND u.level != 0
			LIMIT ?,?
		`, TableH5User, TablePcGroup, FirstTopUpSuccess)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var agentInfo []AgentBasicInfo //代理基本信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlAgentInfo, limit, size).QueryRows(&agentInfo)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statAllDayAgent(t, agentInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

func statAllDayAgent(t int64, agentInfo []AgentBasicInfo) error {
	var (
		startTime, endTime = StartEndTimeByTimestamp(t)
		nowDay             = GetDayByTimestamp(t)    //获取当前时间戳的
		yesterday          = GetYesDayByTimestamp(t) //获取相对于当前时间戳的前一天
	)

	//房卡相关,1-买房卡,2-卖房卡(代充),3-卖房卡(直充),6-系统赠送
	sqlAgentCard := fmt.Sprintf(`
			SELECT
				IF(SUM(card_num) is NULL,0,SUM(card_num)) AS card_num, type
			FROM
				%v
			WHERE
				agent_id = ? AND create_time > %v AND create_time < %v
			GROUP BY
				type
		`, TableH5CardRecord, startTime, endTime)
	//购买房卡的费用(进货的费用),店铺直充(玩家在此代理上购买房卡),代理开通费用
	//从h5_order里统计代理的交易成功的订单金额
	sqlAgentOrder := fmt.Sprintf(`
			SELECT
				IF(SUM(amount) is NULL,0,SUM(amount)) AS agent_order
			FROM
				%v
			WHERE
				uid = ? AND user_type = 1 AND order_time > %v AND order_time < %v AND status >= %v
	`, TableH5Order, startTime, endTime, OrderPaySuccess)
	//从h5_order里统计玩家在此代理的交易成功的订单金额
	sqlPlayerOrder := fmt.Sprintf(`
			SELECT
				IF(SUM(amount) is NULL,0,SUM(amount)) AS player_order
			FROM
				%v
			WHERE
				agent_id = ?  AND order_time > %v AND order_time < %v AND status >= %v
	`, TableH5Order, startTime, endTime, OrderPaySuccess)

	//剩余房卡及可提现金额
	sqlCashCard := fmt.Sprintf(`
			SELECT
				card_num AS rest,amount AS cash
			FROM
				%v
			WHERE
				uid = ?
		`, TableH5CardCash)

	//获取两天前(有可能不是两天前的,因为有可能某天停服了）的统计信息
	sqlTwoDaysBeforeAgent := fmt.Sprintf(`
			SELECT
				buy,give,auto,handle,rest,cash
			FROM
				%v
			WHERE
				create_time = %v AND agent_id = ?
		`, TableDayAgent, yesterday)

	dataZero := make(orm.Params, 2)
	dataZero["create_time"] = nowDay
	dataZero["agent_id"] = 0
	NewOrUpdateChessLog(dataZero, TableDayAgent)

	o := NewDBOrm(DBChessCenter)
	od := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	for _, v := range agentInfo {
		var (
			twoDayAgentRaw                      AgentRaw  //两天前的数据
			yesAgentRaw                         AgentRaw  //昨天的数据
			cardNum                             []CardNum //钻石(1-买房卡,2-卖房卡(代充),3-卖房卡(直充),6-系统赠送)
			rest, cash, agentOrder, playerOrder int64     //剩余房卡,可提现金额,代理订单金额,代理店铺订单金额
		)
		o.Raw(sqlAgentCard, v.Uid).QueryRows(&cardNum)
		for _, cn := range cardNum {
			switch cn.Type {
			case BuyRoomCard:
				yesAgentRaw.Buy = cn.CardNum
			case HandleTopUp:
				yesAgentRaw.Handle = cn.CardNum
			case AutomaticTopUp:
				yesAgentRaw.Auto = cn.CardNum
			case SystemGiveRoomCard:
				yesAgentRaw.Give = cn.CardNum
			}
		}

		o.Raw(sqlAgentOrder, v.Uid).QueryRow(&agentOrder)
		o.Raw(sqlPlayerOrder, v.Uid).QueryRow(&playerOrder)

		o.Raw(sqlCashCard, v.Uid).QueryRow(&rest, &cash)
		od.Raw(sqlTwoDaysBeforeAgent, v.Uid).QueryRow(&twoDayAgentRaw)

		data := map[string]interface{}{
			"create_time":    nowDay,
			"agent_id":       v.Uid,
			"agent_nickname": v.AgentNickname,
			"pid":            v.Pid,
			"level":          v.Level, //1-一级代理,2-二级代理
			"group_id":       v.GroupId,
			"group_name":     v.GroupName,
			"buy":            yesAgentRaw.Buy,
			"buy_growth":     yesAgentRaw.Buy - twoDayAgentRaw.Buy,
			"give":           yesAgentRaw.Give,
			"give_growth":    yesAgentRaw.Give - twoDayAgentRaw.Give,
			"auto":           MathAbs(yesAgentRaw.Auto),
			"auto_growth":    MathAbs(yesAgentRaw.Auto) - twoDayAgentRaw.Auto,
			"handle":         MathAbs(yesAgentRaw.Handle),
			"handle_growth":  MathAbs(yesAgentRaw.Handle) - twoDayAgentRaw.Handle,
			"rest":           rest,
			"rest_growth":    rest - twoDayAgentRaw.Rest,
			"cash":           cash,
			"cash_growth":    cash - twoDayAgentRaw.Cash,

			"agent_order":         agentOrder,
			"agent_order_growth":  agentOrder - twoDayAgentRaw.AgentOrder,
			"player_order":        playerOrder,
			"player_order_growth": playerOrder - twoDayAgentRaw.PlayerOrder,
		}
		NewOrUpdateChessLog(data, TableDayAgent, od)

	}
	//统计今天的数据，全部加起来(重复执行时，不要把自己统计进去了)
	sqlAllAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,

				IF(SUM(agent_order) is NULL,0,SUM(agent_order)) AS agent_order,
				IF(SUM(player_order) is NULL,0,SUM(player_order)) AS player_order,

				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,

				IF(SUM(agent_order_growth) is NULL,0,SUM(agent_order_growth)) AS agent_order_growth,
				IF(SUM(player_order_growth) is NULL,0,SUM(player_order_growth)) AS player_order_growth
			FROM
				%v
			WHERE
				create_time = %v AND agent_id != 0
		`, TableDayAgent, nowDay)
	ol := NewDBOrm(DBChessLog)
	var allAgent []orm.Params
	ol.Raw(sqlAllAgentInfo).Values(&allAgent)
	allAgent[0]["create_time"] = nowDay
	allAgent[0]["agent_id"] = 0
	allAgent[0]["level"] = 0
	allAgent[0]["agent_nickname"] = "全部代理"
	NewOrUpdateChessLog(allAgent[0], TableDayAgent, ol)
	return nil
}

//统计一级代理的数据(日报)
func listDayLevel1Agent(t int64) error {
	day := GetDayByTimestamp(t)
	var count int64 //先统计有多少个正式一级的代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			level = %v AND create_time = %v
	`, TableDayAgent, Level1, day)
	o := NewDBOrm(DBChessLog)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //没有正式代理，统计毛线
		LogPc.Info("暂时没有正式一级代理可以统计")
		return nil
	}
	//代理uid信息
	sqlLevel1 := fmt.Sprintf(`
			SELECT
				agent_id
			FROM
				%v
			WHERE
				level = %v AND create_time = %v
			LIMIT ?,?
		`, TableDayAgent, Level1, day)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var allUid []int64 //代理基本信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlLevel1, limit, size).QueryRows(&allUid)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statDayLevel1Agent(t, allUid)
		if err != nil {
			return err
		}
	}
	return nil
}

//每天凌晨执行，统计昨天的数据
//统计每天一级代理的数据(包括二级代理的数据之和)
func statDayLevel1Agent(t int64, allUid []int64) error {
	var (
		yesterday    = GetDayByTimestamp(t)
		twoDayBefore = GetYesDayByTimestamp(t)
	)
	//昨天一级代理名下的二级代理数量,直接在day_agent里统计
	sqlYesLevel1AgentNum := fmt.Sprintf(`
			SELECT
				COUNT(1) AS agent_num
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableDayAgent, yesterday)
	//两天前一级代理名下的二级代理数量,直接在day_agent里统计
	sqlTwoDayLevel1AgentNum := fmt.Sprintf(`
			SELECT
				COUNT(1) AS agent_num
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableDayAgent, twoDayBefore)

	//统计一级代理名下二级代理的数据(因为一级代理的数据包括了一级代理本身及名下的二级代理的总和)
	//统计了一级代理及名下二级代理的数据之和
	sqlYesLevel2AgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,
				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableDayAgent, yesterday)
	//一级代理本身的数据
	sqlYesSelfAgentInfo := fmt.Sprintf(`
			SELECT
				*
			FROM
				%v
			WHERE
				agent_id = ? AND create_time = %v
		`, TableDayAgent, yesterday)

	dataZero := make(orm.Params, 2)
	dataZero["create_time"] = yesterday
	dataZero["agent_id"] = 0
	NewOrUpdateChessLog(dataZero, TableDayAgentLevel1)

	o := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	for _, uid := range allUid {
		var (
			yesLevel2Agent              AgentStat //昨天的数据(一级代理名下所有二级代理）
			yesSelfAgent                AgentAll  //昨天的数据(一级代理本身的）
			yesAgentNum, twoDayAgentNum int64     //昨天代理数量,两天前的代理数量
		)

		//统计昨天代理数量
		o.Raw(sqlYesLevel1AgentNum, uid).QueryRow(&yesAgentNum)

		//统计两天前的代理数量
		o.Raw(sqlTwoDayLevel1AgentNum, uid).QueryRow(&twoDayAgentNum)

		err := o.Raw(sqlYesLevel2AgentInfo, uid).QueryRow(&yesLevel2Agent)
		if err != nil {
			LogClient.Error(err.Error())
		}

		err = o.Raw(sqlYesSelfAgentInfo, uid).QueryRow(&yesSelfAgent)
		if err != nil {
			LogClient.Error(err.Error())
		}

		data := map[string]interface{}{
			"create_time":    yesSelfAgent.CreateTime,
			"agent_id":       yesSelfAgent.AgentId,
			"agent_nickname": yesSelfAgent.AgentNickname,
			"group_id":       yesSelfAgent.GroupId,
			"group_name":     yesSelfAgent.GroupName,

			"buy":              yesLevel2Agent.Buy + yesSelfAgent.Buy,
			"buy_growth":       yesLevel2Agent.BuyGrowth + yesSelfAgent.BuyGrowth,
			"give":             yesLevel2Agent.Give + yesSelfAgent.Give,
			"give_growth":      yesLevel2Agent.GiveGrowth + yesSelfAgent.GiveGrowth,
			"auto":             yesLevel2Agent.Auto + yesSelfAgent.Auto,
			"auto_growth":      yesLevel2Agent.AutoGrowth + yesSelfAgent.AutoGrowth,
			"handle":           yesLevel2Agent.Handle + yesSelfAgent.Handle,
			"handle_growth":    yesLevel2Agent.HandleGrowth + yesSelfAgent.HandleGrowth,
			"rest":             yesLevel2Agent.Rest + yesSelfAgent.Rest,
			"rest_growth":      yesLevel2Agent.RestGrowth + yesSelfAgent.RestGrowth,
			"cash":             yesLevel2Agent.Cash + yesSelfAgent.Cash,
			"cash_growth":      yesLevel2Agent.CashGrowth + yesSelfAgent.CashGrowth,
			"agent_num":        yesAgentNum,
			"agent_num_growth": yesAgentNum - twoDayAgentNum,
		}
		NewOrUpdateChessLog(data, TableDayAgentLevel1, o)

	}
	//统计今天的数据，全部加起来(重复执行时，不要把自己统计进去了)
	sqlAllAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,
				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,
				IF(SUM(agent_num) is NULL,0,SUM(agent_num)) AS agent_num,
				IF(SUM(agent_num_growth) is NULL,0,SUM(agent_num_growth)) AS agent_num_growth
			FROM
				%v
			WHERE
				create_time = %v AND agent_id != 0
		`, TableDayAgentLevel1, yesterday)
	ol := NewDBOrm(DBChessLog)
	var allAgent []orm.Params
	ol.Raw(sqlAllAgentInfo).Values(&allAgent)
	allAgent[0]["create_time"] = yesterday
	allAgent[0]["agent_id"] = 0
	allAgent[0]["agent_nickname"] = "全部一级代理"
	NewOrUpdateChessLog(allAgent[0], TableDayAgentLevel1, ol)
	return nil
}

//统计大区(日报)
func listDayGroup(t int64) error {
	var count int64 //先统计有多少个正式一级的代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
	`, TablePcGroup)
	o := NewDBOrm(DBChessCenter)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //没有大区，统计毛线
		LogPc.Info("暂时没有大区可以统计")
		return nil
	}
	sqlGroup := fmt.Sprintf(`
			SELECT
				id,name
			FROM
				%v
			LIMIT ?,?
		`, TablePcGroup)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var allGroup []Group //大区的信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlGroup, limit, size).QueryRows(&allGroup)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statDayGroup(t, allGroup)
		if err != nil {
			return err
		}
	}
	return nil
}

//每天凌晨执行，统计昨天的数据
//统计每天每个大区消耗的房卡,收入方面
func statDayGroup(t int64, allGroup []Group) error {
	var (
		yesterday    = GetDayByTimestamp(t)
		twoDayBefore = GetYesDayByTimestamp(t)
	)

	//昨天的数量大区名下一级代理及二级代理数量(day_agent)
	sqlYesterdayGroupAgentNum := fmt.Sprintf(`
			SELECT
				COUNT(1) AS agent_num
			FROM
				%v
			WHERE
				 group_id = ? AND  create_time = %v
		`, TableDayAgent, yesterday)
	//两天前的大区名下一级代理及二级代理数量(day_group)
	sqlTwoDayGroupAgentNum := fmt.Sprintf(`
			SELECT
				agent_num
			FROM
				%v
			WHERE
				group_id = ? AND create_time = %v
		`, TableDayGroup, twoDayBefore)

	//统计大区名下的一级代理的数据(因为一级代理的数据包括了一级代理本身及名下的二级代理的总和)
	sqlYesAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,

				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth
			FROM
				%v
			WHERE
				create_time = %v AND group_id = ?
		`, TableDayAgentLevel1, yesterday)
	//统计大区名下所有代理的数据,所以到day_agent表统计
	sqlYesBonus := fmt.Sprintf(`
			SELECT
				IF(SUM(agent_order) is NULL,0,SUM(agent_order)) AS agent_order,
				IF(SUM(player_order) is NULL,0,SUM(player_order)) AS player_order,

				IF(SUM(agent_order_growth) is NULL,0,SUM(agent_order_growth)) AS agent_order_growth,
				IF(SUM(player_order_growth) is NULL,0,SUM(player_order_growth)) AS player_order_growth
			FROM
				%v
			WHERE
				create_time = %v AND group_id = ?
	`, TableDayAgent, yesterday)

	//统计大区名下所有代理的数据(2天前的数据),所以到day_agent表统计
	sqlTwoDayBonus := fmt.Sprintf(`
			SELECT
				bonus
			FROM
				%v
			WHERE
				create_time = %v AND group_id = ?
	`, TableDayGroup, twoDayBefore)

	r, err := h5.RuleByType(RuleGroupBonus)
	if err != nil {
		LogPc.Warning(fmt.Sprintf("大区分成比例获取失败:%v", err))
	}
	if r.Id == 0 {
		LogPc.Warning("大区分成比例获取没有设置,请及时设置")
	}

	o := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	for _, v := range allGroup {
		var (
			yesterdayAgentNum, twoDayAgentNum, twoDayBonus int64      //截止于昨天的代理数量,两天前的代理数量
			yesAgentInfo                                   AgentAll   //统计昨天代理的数据
			yesAgentBonus                                  AgentBonus //统计大区名下所有代理的提成
		)
		//统计大区名下所有代理的提成
		o.Raw(sqlYesBonus, v.Id).QueryRow(&yesAgentBonus)
		o.Raw(sqlTwoDayBonus, v.Id).QueryRow(&twoDayBonus)

		//统计昨天代理数量
		o.Raw(sqlYesterdayGroupAgentNum, v.Id).QueryRow(&yesterdayAgentNum)

		//统计两天前的代理数量
		o.Raw(sqlTwoDayGroupAgentNum, v.Id).QueryRow(&twoDayAgentNum)

		o.Raw(sqlYesAgentInfo, v.Id).QueryRow(&yesAgentInfo)

		data := map[string]interface{}{
			"create_time":      yesterday,
			"group_id":         v.Id,
			"group_name":       v.Name,
			"buy":              yesAgentInfo.Buy,
			"buy_growth":       yesAgentInfo.BuyGrowth,
			"give":             yesAgentInfo.Give,
			"give_growth":      yesAgentInfo.GiveGrowth,
			"auto":             yesAgentInfo.Auto,
			"auto_growth":      yesAgentInfo.AutoGrowth,
			"handle":           yesAgentInfo.Handle,
			"handle_growth":    yesAgentInfo.HandleGrowth,
			"rest":             yesAgentInfo.Rest,
			"rest_growth":      yesAgentInfo.RestGrowth,
			"cash":             yesAgentInfo.Cash,
			"cash_growth":      yesAgentInfo.CashGrowth,
			"agent_num":        yesterdayAgentNum,
			"agent_num_growth": yesterdayAgentNum - twoDayAgentNum,

			"agent_order":         yesAgentBonus.AgentOrder,
			"agent_order_growth":  yesAgentBonus.AgentOrderGrowth,
			"player_order":        yesAgentBonus.PlayerOrder,
			"player_order_growth": yesAgentBonus.PlayerOrderGrowth,

			"bonus": float64(r.Amount) / float64(10000) *
				float64(yesAgentBonus.AgentOrder+yesAgentBonus.PlayerOrder), //提成金额
			"bonus_rate":   r.Amount, //提成比例
			"bonus_growth": yesAgentBonus.AgentOrder + yesAgentBonus.PlayerOrder - twoDayBonus,
		}
		NewOrUpdateChessLog(data, TableDayGroup, o)

	}
	//统计今天的数据，全部加起来(重复执行时，不能把自己也统计进去了)
	sqlAllGroupInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,

				IF(SUM(agent_order) is NULL,0,SUM(agent_order)) AS agent_order,
				IF(SUM(player_order) is NULL,0,SUM(player_order)) AS player_order,
				IF(SUM(bonus) is NULL,0,SUM(bonus)) AS bonus,

				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,
				IF(SUM(agent_num) is NULL,0,SUM(agent_num)) AS agent_num,
				IF(SUM(agent_num_growth) is NULL,0,SUM(agent_num_growth)) AS agent_num_growth,

				IF(SUM(agent_order_growth) is NULL,0,SUM(agent_order_growth)) AS agent_order_growth,
				IF(SUM(player_order_growth) is NULL,0,SUM(player_order_growth)) AS player_order_growth,
				IF(SUM(bonus_growth) is NULL,0,SUM(bonus_growth)) AS bonus_growth
			FROM
				%v
			WHERE
				create_time = %v AND group_id != 0
		`, TableDayGroup, yesterday)
	ol := NewDBOrm(DBChessLog)
	var allGroupInfo []orm.Params
	ol.Raw(sqlAllGroupInfo).Values(&allGroupInfo)
	allGroupInfo[0]["create_time"] = yesterday
	allGroupInfo[0]["group_id"] = 0
	allGroupInfo[0]["group_name"] = "全部区域"
	allGroupInfo[0]["bonus_rate"] = r.Amount
	NewOrUpdateChessLog(allGroupInfo[0], TableDayGroup, ol)

	return nil
}

//统计所有代理的(月报表)
func listAllMonthAgent(t int64) error {
	day := GetDayByTimestamp(t) //当前时间戳20180314
	var count int64             //先统计有多少个正式的代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			create_time = %v
	`, TableDayAgent, day)
	o := NewDBOrm(DBChessLog)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //当天没有代理，统计毛线
		LogPc.Info("当天暂时没有代理可以统计")
		return nil
	}
	//代理基本信息(直接在day_agent里取就行了),pid,nickname,group_id,group_name
	sqlAgentInfo := fmt.Sprintf(`
			SELECT
				agent_id AS uid,pid,agent_nickname,group_id,level,group_name
			FROM
				%v
			WHERE
			 	create_time = %v
			LIMIT ?,?
		`, TableDayAgent, day)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var agentInfo []AgentBasicInfo //代理基本信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlAgentInfo, limit, size).QueryRows(&agentInfo)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statMonthAgent(t, agentInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

//统计月报表(month_agent)
func statMonthAgent(t int64, agentInfo []AgentBasicInfo) error {
	var (
		yesterday = GetDayByTimestamp(t)    //当前时间戳20180314
		thisMonth = ThisMonthByTimestamp(t) //当前时间戳的所在月201803
		lastMonth = LastMonthByTimestamp(t) //当前时间戳所在月的上一个月201802
	)
	//获取昨天的数据，然后加到这个月去
	sqlYesDayAgent := fmt.Sprintf(`
		SELECT
			buy,give,auto,handle,rest,cash,agent_order,player_order
		FROM
			%v
		WHERE
			agent_id = ? AND create_time = %v
	`, TableDayAgent, yesterday)
	//获取上一个月的数据部分数据
	sqlLastMonthDayAgent := fmt.Sprintf(`
		SELECT
			buy,give,auto,handle,rest,cash,agent_order,player_order
		FROM
			%v
		WHERE
			agent_id = ? AND create_time = %v
	`, TableMonthAgent, lastMonth)
	o := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	updateData := make(orm.Params, 4)
	for _, v := range agentInfo {
		var (
			yesAgentInfo       AgentRaw
			lastMonthAgentInfo AgentRaw
		)
		//昨天的数据
		o.Raw(sqlYesDayAgent, v.Uid).QueryRow(&yesAgentInfo)
		//上个月的数据
		o.Raw(sqlLastMonthDayAgent, v.Uid).QueryRow(&lastMonthAgentInfo)

		data := map[string]interface{}{
			"buy":          yesAgentInfo.Buy,
			"give":         yesAgentInfo.Give,
			"auto":         yesAgentInfo.Auto,
			"handle":       yesAgentInfo.Handle,
			"agent_order":  yesAgentInfo.AgentOrder,
			"player_order": yesAgentInfo.PlayerOrder,

			"buy_growth":          yesAgentInfo.Buy,         //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"give_growth":         yesAgentInfo.Give,        //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"auto_growth":         yesAgentInfo.Auto,        //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"handle_growth":       yesAgentInfo.Handle,      //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"agent_order_growth":  yesAgentInfo.AgentOrder,  //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"player_order_growth": yesAgentInfo.PlayerOrder, //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
		}

		//增量增加的
		//TODO:有个问题，如果data里的数据全为0那么n一样等于0,相当于今天统计的数据是1号的
		n, err := UpdateAddMonthAgent(data, v.Uid, thisMonth, TableMonthAgent, o)
		if err != nil {
			LogClient.Error(err.Error())
			return err
		}
		if n != 1 { //说明这个月还没有生成，所以要先新建一个
			//LogPc.Debug("-------------进入1号-----------------")
			//只有每个月的1号时才是没有的(或产品刚上线时不是1号,那时肯定没有记录
			//每个月的1号,先占一坑位，因为我想把agent_id=0的排在最前面
			dataZero := make(orm.Params, 2)
			dataZero["create_time"] = thisMonth
			dataZero["agent_id"] = 0
			NewOrUpdateChessLog(dataZero, TableMonthAgent, o)

			//这几个不能增量加
			data["create_time"] = thisMonth
			data["agent_id"] = v.Uid
			data["level"] = v.Level
			data["pid"] = v.Pid
			data["agent_nickname"] = v.AgentNickname
			data["group_id"] = v.GroupId
			data["group_name"] = v.GroupName

			//每个月的一号的数据全部数据就是1号这一天的，所以可以直接用1号的数据减去上一个月整个月的数据
			data["buy_growth"] = yesAgentInfo.Buy - lastMonthAgentInfo.Buy
			data["give_growth"] = yesAgentInfo.Give - lastMonthAgentInfo.Give
			data["auto_growth"] = yesAgentInfo.Auto - lastMonthAgentInfo.Auto
			data["handle_growth"] = yesAgentInfo.Handle - lastMonthAgentInfo.Handle

			data["cash"] = yesAgentInfo.Cash
			data["cash_growth"] = yesAgentInfo.Cash - lastMonthAgentInfo.Cash
			data["rest"] = yesAgentInfo.Rest
			data["rest_growth"] = yesAgentInfo.Rest - lastMonthAgentInfo.Rest

			data["agent_order"] = yesAgentInfo.AgentOrder
			data["agent_order_growth"] = yesAgentInfo.AgentOrder - lastMonthAgentInfo.AgentOrder
			data["player_order"] = yesAgentInfo.PlayerOrder
			data["player_order_growth"] = yesAgentInfo.PlayerOrder - lastMonthAgentInfo.PlayerOrder
			NewMonth(data, TableMonthAgent, o)
		} else {
			//LogPc.Debug("-------------进入不是1号-----------------")
			//TODO:直接覆盖的,这个要再次确认需求
			updateData["cash"] = yesAgentInfo.Cash
			updateData["cash_growth"] = yesAgentInfo.Cash - lastMonthAgentInfo.Cash
			updateData["rest"] = yesAgentInfo.Rest
			updateData["rest_growth"] = yesAgentInfo.Rest - lastMonthAgentInfo.Rest
			UpdateMonthAgent(updateData, v.Uid, thisMonth, TableMonthAgent, o)
		}

	}
	//统计这个月的数据，全部加起来(重复执行时，不能把自己也统计进去了，所以agent_id != 0)
	sqlAllAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,

				IF(SUM(agent_order) is NULL,0,SUM(agent_order)) AS agent_order,
				IF(SUM(player_order) is NULL,0,SUM(player_order)) AS player_order,

				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,

				IF(SUM(agent_order_growth) is NULL,0,SUM(agent_order_growth)) AS agent_order_growth,
				IF(SUM(player_order_growth) is NULL,0,SUM(player_order_growth)) AS player_order_growth
			FROM
				%v
			WHERE
				create_time = %v AND agent_id != 0
		`, TableMonthAgent, thisMonth)
	ol := NewDBOrm(DBChessLog)
	var allAgent []orm.Params
	ol.Raw(sqlAllAgentInfo).Values(&allAgent)
	allAgent[0]["agent_id"] = 0
	allAgent[0]["level"] = 0
	allAgent[0]["create_time"] = thisMonth
	allAgent[0]["agent_nickname"] = "全部代理"
	NewOrUpdateChessLog(allAgent[0], TableMonthAgent, ol)
	return nil
}

//统计所有一级代理的(月报表)
func listMonthLevel1Agent(t int64) error {
	thisMonth := ThisMonthByTimestamp(t) //当前时间戳的所在月201803
	var count int64                      //先统计有多少个正式一级代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			create_time = %v AND level = %v
	`, TableMonthAgent, thisMonth, Level1)
	o := NewDBOrm(DBChessLog)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //当天没有代理，统计毛线
		LogPc.Info("当天暂时没有代理可以统计")
		return nil
	}
	//代理基本信息(直接在month_agent里取就行了)agent_nickname,group_id,group_name
	sqlAgentInfo := fmt.Sprintf(`
			SELECT
				agent_id AS uid,agent_nickname,group_id,group_name
			FROM
				%v
			WHERE
			 	create_time = %v AND level = %v
			LIMIT ?,?
		`, TableMonthAgent, thisMonth, Level1)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var agentInfo []AgentBasicInfo //代理基本信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlAgentInfo, limit, size).QueryRows(&agentInfo)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statMonthLevel1Agent(t, agentInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

//统计一级代理月报表(month_agent_level1)
func statMonthLevel1Agent(t int64, agentInfo []AgentBasicInfo) error {
	var (
		thisMonth = ThisMonthByTimestamp(t) //当前时间戳的所在月201803
		lastMonth = LastMonthByTimestamp(t) //当前时间戳的所在上个月201802
	)

	//本月一级代理名下的二级代理数量,直接在month_agent里统计
	sqlThisMonthAgentNum := fmt.Sprintf(`
			SELECT
				COUNT(1) AS agent_num
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableMonthAgent, thisMonth)
	//上个月一级代理名下的二级代理数量,直接在day_agent里统计
	sqlLastMonthAgentNum := fmt.Sprintf(`
			SELECT
				COUNT(1) AS agent_num
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableMonthAgent, lastMonth)

	//统计一级代理名下二级代理的数据(因为一级代理的数据包括了一级代理本身及名下的二级代理的总和)
	//统计了一级代理及名下二级代理的数据之和
	sqlLevel2AgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,
				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth
			FROM
				%v
			WHERE
				pid = ? AND create_time = %v
		`, TableMonthAgent, thisMonth)
	//一级代理本身的数据
	sqlSelfAgentInfo := fmt.Sprintf(`
			SELECT
				*
			FROM
				%v
			WHERE
				agent_id = ? AND create_time = %v
		`, TableMonthAgent, thisMonth)

	dataZero := make(orm.Params, 2)
	dataZero["create_time"] = thisMonth
	dataZero["agent_id"] = 0
	NewOrUpdateChessLog(dataZero, TableMonthAgentLevel1)

	o := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	for _, v := range agentInfo {
		var (
			Level2Agent                          AgentStat //当前时间戳的数据(一级代理名下所有二级代理）
			SelfAgent                            AgentAll  //当前时间戳的昨天的数据(一级代理本身的）
			thisMonthAgentNum, lastMonthAgentNum int64     //当月代理数量,上个月的代理数量
		)

		o.Raw(sqlThisMonthAgentNum, v.Uid).QueryRow(&thisMonthAgentNum)
		o.Raw(sqlLastMonthAgentNum, v.Uid).QueryRow(&lastMonthAgentNum)

		o.Raw(sqlLevel2AgentInfo, v.Uid).QueryRow(&Level2Agent)
		o.Raw(sqlSelfAgentInfo, v.Uid).QueryRow(&SelfAgent)

		data := map[string]interface{}{
			"create_time":    thisMonth,
			"agent_id":       v.Uid,
			"agent_nickname": v.AgentNickname,
			"group_id":       v.GroupId,
			"group_name":     v.GroupName,

			"buy":              Level2Agent.Buy + SelfAgent.Buy,
			"buy_growth":       Level2Agent.BuyGrowth + SelfAgent.BuyGrowth,
			"give":             Level2Agent.Give + SelfAgent.Give,
			"give_growth":      Level2Agent.GiveGrowth + SelfAgent.GiveGrowth,
			"auto":             Level2Agent.Auto + SelfAgent.Auto,
			"auto_growth":      Level2Agent.AutoGrowth + SelfAgent.AutoGrowth,
			"handle":           Level2Agent.Handle + SelfAgent.Handle,
			"handle_growth":    Level2Agent.HandleGrowth + SelfAgent.HandleGrowth,
			"rest":             Level2Agent.Rest + SelfAgent.Rest,
			"rest_growth":      Level2Agent.RestGrowth + SelfAgent.RestGrowth,
			"cash":             Level2Agent.Cash + SelfAgent.Cash,
			"cash_growth":      Level2Agent.CashGrowth + SelfAgent.CashGrowth,
			"agent_num":        thisMonthAgentNum,
			"agent_num_growth": thisMonthAgentNum - lastMonthAgentNum,
		}
		NewOrUpdateChessLog(data, TableMonthAgentLevel1, o)
	}
	//统计这个月的数据，全部加起来(重复执行时，不能把自己也统计进去了，所以agent_id != 0)
	sqlAllAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,
				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,
				IF(SUM(agent_num) is NULL,0,SUM(agent_num)) AS agent_num,
				IF(SUM(agent_num_growth) is NULL,0,SUM(agent_num_growth)) AS agent_num_growth
			FROM
				%v
			WHERE
				create_time = %v AND agent_id != 0
		`, TableMonthAgentLevel1, thisMonth)
	ol := NewDBOrm(DBChessLog)
	var allAgent []orm.Params
	ol.Raw(sqlAllAgentInfo).Values(&allAgent)
	allAgent[0]["agent_id"] = 0
	allAgent[0]["create_time"] = thisMonth
	allAgent[0]["agent_nickname"] = "全部代理"
	NewOrUpdateChessLog(allAgent[0], TableMonthAgentLevel1, ol)
	return nil
}

//统计大区月报表(month_group)
func listMonthGroup(t int64) error {
	day := GetDayByTimestamp(t) //当前时间戳20180314
	var count int64             //先统计有多少个正式的代理
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			create_time = %v
	`, TableDayGroup, day)
	o := NewDBOrm(DBChessLog)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //当天没有代理，统计毛线
		LogPc.Info("当天暂时没有大区可以统计")
		return nil
	}
	//大区基本信息(直接在day_group里获取),pid,nickname,group_id,group_name
	sqlAgentInfo := fmt.Sprintf(`
			SELECT
				group_id AS id,group_name AS name
			FROM
				%v
			WHERE
			 	create_time = %v
			LIMIT ?,?
		`, TableDayGroup, day)
	var i, index, size int64
	size = 10 //每次取10个
	for index = 1; i < count; index++ {
		var allGroup []Group //大区基本信息
		limit := (index - 1) * size
		n, err := o.Raw(sqlAgentInfo, limit, size).QueryRows(&allGroup)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = statMonthGroup(t, allGroup)
		if err != nil {
			return err
		}
	}
	return nil
}

//统计大区月报表(month_group)
func statMonthGroup(t int64, allGroup []Group) error {
	var (
		yesterday = GetDayByTimestamp(t)    //当前时间戳20180314
		thisMonth = ThisMonthByTimestamp(t) //当前时间戳的所在月201803
		lastMonth = LastMonthByTimestamp(t) //当前时间戳所在月的上一个月201802
	)

	//获取昨天的数据，然后加到这个月去
	sqlYesDayGroup := fmt.Sprintf(`
		SELECT
			buy,give,auto,handle,rest,cash,agent_num,agent_order,player_order,bonus
		FROM
			%v
		WHERE
			group_id = ? AND create_time = %v
	`, TableDayGroup, yesterday)
	//获取上一个月的数据部分数据
	sqlLastMonthDayGroup := fmt.Sprintf(`
		SELECT
			buy,give,auto,handle,rest,cash,agent_num,agent_order,player_order,bonus
		FROM
			%v
		WHERE
			group_id = ? AND create_time = %v
	`, TableMonthGroup, lastMonth)

	o := NewDBOrm(DBChessLog)
	//一条一条的数据查找统计写入今天的表里
	updateData := make(orm.Params, 6)
	for _, v := range allGroup {
		var (
			yesGroupInfo       AgentRaw
			lastMonthGroupInfo AgentRaw
		)
		o.Raw(sqlYesDayGroup, v.Id).QueryRow(&yesGroupInfo)
		o.Raw(sqlLastMonthDayGroup, v.Id).QueryRow(&lastMonthGroupInfo)
		data := map[string]interface{}{
			"buy":    yesGroupInfo.Buy,
			"give":   yesGroupInfo.Give,
			"auto":   yesGroupInfo.Auto,
			"handle": yesGroupInfo.Handle,

			"agent_order":  yesGroupInfo.AgentOrder,
			"player_order": yesGroupInfo.PlayerOrder,
			"bonus":        yesGroupInfo.Bonus,

			"buy_growth":    yesGroupInfo.Buy,    //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"give_growth":   yesGroupInfo.Give,   //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"auto_growth":   yesGroupInfo.Auto,   //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率
			"handle_growth": yesGroupInfo.Handle, //根据数学公式,可以直接增量想加就是本月对比上一个月的增长率

			"agent_order_growth":  yesGroupInfo.AgentOrder,
			"player_order_growth": yesGroupInfo.PlayerOrder,
			"bonus_growth":        yesGroupInfo.Bonus,
		}
		//增量增加的
		n, err := UpdateAddMonthGroup(data, v.Id, thisMonth, TableMonthGroup, o)
		if err != nil {
			LogClient.Error(err.Error())
			return err
		}
		if n != 1 {
			//每个月的1号,先占一坑位，因为我想把agent_id=0的排在最前面
			dataZero := make(orm.Params, 2)
			dataZero["create_time"] = thisMonth
			dataZero["group_id"] = 0
			NewOrUpdateChessLog(dataZero, TableMonthGroup, o)

			//这几个不能增量加
			data["create_time"] = thisMonth
			data["group_id"] = v.Id
			data["group_name"] = v.Name

			//每个月的一号的数据全部数据就是1号这一天的，所以可以直接用1号的数据减去上一个月整个月的数据
			data["buy_growth"] = yesGroupInfo.Buy - lastMonthGroupInfo.Buy
			data["give_growth"] = yesGroupInfo.Give - lastMonthGroupInfo.Give
			data["auto_growth"] = yesGroupInfo.Auto - lastMonthGroupInfo.Auto
			data["handle_growth"] = yesGroupInfo.Handle - lastMonthGroupInfo.Handle

			data["cash"] = yesGroupInfo.Cash
			data["cash_growth"] = yesGroupInfo.Cash - lastMonthGroupInfo.Cash
			data["rest"] = yesGroupInfo.Rest
			data["rest_growth"] = yesGroupInfo.Rest - lastMonthGroupInfo.Rest
			data["agent_num"] = yesGroupInfo.AgentNum
			data["agent_num_growth"] = yesGroupInfo.AgentNum - lastMonthGroupInfo.AgentNum

			data["agent_order"] = yesGroupInfo.AgentOrder
			data["agent_order_growth"] = yesGroupInfo.AgentOrder - lastMonthGroupInfo.AgentOrder
			data["player_order"] = yesGroupInfo.PlayerOrder
			data["player_order_growth"] = yesGroupInfo.PlayerOrder - lastMonthGroupInfo.PlayerOrder
			data["bonus"] = yesGroupInfo.Bonus
			data["bonus_growth"] = yesGroupInfo.Bonus - lastMonthGroupInfo.Bonus

			NewMonth(data, TableMonthGroup, o)
			//每个月的一号的数据全部数据就是1号这一天的，所以可以直接用1号的数据减去上一个月整个月的数据
		} else {
			//直接覆盖的,这个不需要累加
			updateData["cash"] = yesGroupInfo.Cash
			updateData["cash_growth"] = yesGroupInfo.Cash - lastMonthGroupInfo.Cash
			updateData["rest"] = yesGroupInfo.Rest
			updateData["rest_growth"] = yesGroupInfo.Rest - lastMonthGroupInfo.Rest
			updateData["agent_num"] = yesGroupInfo.AgentNum
			updateData["agent_num_growth"] = yesGroupInfo.AgentNum - lastMonthGroupInfo.AgentNum
			UpdateMonthGroup(updateData, v.Id, thisMonth, TableMonthGroup, o)
		}

	}
	//统计这个月的数据，全部加起来(重复执行时，不能把自己也统计进去了，所以group_id != 0)
	sqlAllAgentInfo := fmt.Sprintf(`
			SELECT
				IF(SUM(buy) is NULL,0,SUM(buy)) AS buy,IF(SUM(give) is NULL,0,SUM(give)) AS give,
				IF(SUM(auto) is NULL,0,SUM(auto)) AS auto,IF(SUM(handle) is NULL,0,SUM(handle)) AS handle,
				IF(SUM(rest) is NULL,0,SUM(rest)) AS rest,IF(SUM(cash) is NULL,0,SUM(cash)) AS cash,

				IF(SUM(agent_order) is NULL,0,SUM(agent_order)) AS agent_order,
				IF(SUM(player_order) is NULL,0,SUM(player_order)) AS player_order,
				IF(SUM(bonus) is NULL,0,SUM(bonus)) AS bonus,

				IF(SUM(buy_growth) is NULL,0,SUM(buy_growth)) AS buy_growth,
				IF(SUM(give_growth) is NULL,0,SUM(give_growth)) AS give_growth,
				IF(SUM(auto_growth) is NULL,0,SUM(auto_growth)) AS auto_growth,
				IF(SUM(handle_growth) is NULL,0,SUM(handle_growth)) AS handle_growth,
				IF(SUM(cash_growth) is NULL,0,SUM(cash_growth)) AS cash_growth,
				IF(SUM(rest_growth) is NULL,0,SUM(rest_growth)) AS rest_growth,
				IF(SUM(agent_num) is NULL,0,SUM(agent_num)) AS agent_num,
				IF(SUM(agent_num_growth) is NULL,0,SUM(agent_num_growth)) AS agent_num_growth,

				IF(SUM(agent_order_growth) is NULL,0,SUM(agent_order_growth)) AS agent_order_growth,
				IF(SUM(player_order_growth) is NULL,0,SUM(player_order_growth)) AS player_order_growth,
				IF(SUM(bonus_growth) is NULL,0,SUM(bonus_growth)) AS bonus_growth
			FROM
				%v
			WHERE
				create_time = %v AND group_id != 0
		`, TableMonthGroup, thisMonth)
	ol := NewDBOrm(DBChessLog)
	var allAgent []orm.Params
	ol.Raw(sqlAllAgentInfo).Values(&allAgent)
	allAgent[0]["create_time"] = thisMonth
	allAgent[0]["group_id"] = 0
	allAgent[0]["group_name"] = "全部区域"
	NewOrUpdateChessLog(allAgent[0], TableMonthGroup, ol)
	return nil
}
